<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>运维管理系统 - 主机管理</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #3498db;
            --secondary: #2c3e50;
            --success: #27ae60;
            --warning: #f39c12;
            --danger: #e74c3c;
            --light: #ecf0f1;
            --dark: #34495e;
            --gray: #95a5a6;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background-color: #f5f7fa;
            color: #333;
            display: flex;
            min-height: 100vh;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: 250px;
            background: var(--secondary);
            color: white;
            height: 100vh;
            position: fixed;
            padding: 20px 0;
            box-shadow: 3px 0 10px rgba(0, 0, 0, 0.1);
            z-index: 100;
        }

        .logo {
            padding: 0 20px 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 20px;
        }

        .logo h1 {
            font-size: 1.5rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .logo h1 i {
            color: var(--primary);
        }

        .nav-links {
            list-style: none;
        }

        .nav-links li {
            padding: 12px 20px;
            transition: all 0.3s;
        }

        .nav-links li.active {
            background: rgba(52, 152, 219, 0.2);
            border-left: 4px solid var(--primary);
        }

        .nav-links li:hover:not(.active) {
            background: rgba(255, 255, 255, 0.1);
        }

        .nav-links a {
            color: white;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 15px;
            font-size: 1rem;
        }

        /* 主内容区域 */
        .main-content {
            flex: 1;
            margin-left: 250px;
            padding: 20px;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 0;
            margin-bottom: 20px;
            border-bottom: 1px solid #e0e6ed;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--primary);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }

        .page-title {
            font-size: 1.8rem;
            color: var(--dark);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        /* 卡片样式 */
        .card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            margin-bottom: 25px;
            overflow: hidden;
        }

        .card-header {
            padding: 20px;
            border-bottom: 1px solid #e0e6ed;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: var(--dark);
        }

        .card-body {
            padding: 20px;
        }

        /* 主机卡片样式 */
        .host-card {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }

        .host-item {
            border: 1px solid #e0e6ed;
            border-radius: 8px;
            padding: 15px;
            transition: transform 0.3s, box-shadow 0.3s;
            cursor: pointer;
        }

        .host-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
        }

        .host-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .host-name {
            font-weight: 600;
            font-size: 1.1rem;
            color: var(--dark);
        }

        .host-status {
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .host-status.online {
            background: rgba(39, 174, 96, 0.15);
            color: var(--success);
        }

        .host-status.offline {
            background: rgba(231, 76, 60, 0.15);
            color: var(--danger);
        }

        .host-ip {
            color: var(--gray);
            font-size: 0.9rem;
            margin-bottom: 10px;
        }

        .host-details {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            margin: 15px 0;
        }

        .metric {
            text-align: center;
        }

        .metric-value {
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 5px;
        }

        .metric-label {
            font-size: 0.8rem;
            color: var(--gray);
        }

        .host-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin-top: 10px;
        }

        .tag {
            background: rgba(52, 152, 219, 0.1);
            color: var(--primary);
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
        }

        /* 按钮样式 */
        .btn {
            padding: 8px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }

        .btn-primary {
            background: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background: #2980b9;
        }

        .btn-success {
            background: var(--success);
            color: white;
        }

        .btn-danger {
            background: var(--danger);
            color: white;
        }

        .btn-light {
            background: var(--light);
            color: var(--dark);
        }

        /* 表单样式 */
        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--dark);
        }

        .form-control {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 1rem;
            transition: border 0.3s;
        }

        .form-control:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }

        /* 表格样式 */
        .table {
            width: 100%;
            border-collapse: collapse;
        }

        .table th, .table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #e0e6ed;
        }

        .table th {
            background: #f8f9fa;
            font-weight: 600;
            color: var(--dark);
        }

        .table tr:hover {
            background: #f8f9fa;
        }

        /* 执行命令区域 */
        .command-container {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }

        .command-input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-family: monospace;
        }

        .output-panel {
            background: #1e1e1e;
            color: #d4d4d4;
            padding: 15px;
            border-radius: 5px;
            font-family: monospace;
            white-space: pre-wrap;
            max-height: 300px;
            overflow: auto;
            margin-top: 15px;
        }

        /* 响应式调整 */
        @media (max-width: 992px) {
            .sidebar {
                width: 70px;
            }

            .logo h1 span, .nav-links a span {
                display: none;
            }

            .logo {
                text-align: center;
                padding: 10px 0 20px;
            }

            .nav-links li {
                text-align: center;
                padding: 15px 0;
            }

            .nav-links a {
                justify-content: center;
            }

            .main-content {
                margin-left: 70px;
            }
        }

        @media (max-width: 768px) {
            .host-card {
                grid-template-columns: 1fr;
            }

            .header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }
        }
    </style>
</head>
<body>
    <!-- 侧边导航 -->
    <div class="sidebar">
        <div class="logo">
            <h1><i class="fas fa-server"></i> <span>运维管理系统</span></h1>
        </div>
        <ul class="nav-links">
            <li class="active">
                <a href="#"><i class="fas fa-tachometer-alt"></i> <span>仪表盘</span></a>
            </li>
            <li>
                <a href="#"><i class="fas fa-server"></i> <span>主机管理</span></a>
            </li>
            <li>
                <a href="#"><i class="fas fa-network-wired"></i> <span>网络设备</span></a>
            </li>
            <li>
                <a href="#"><i class="fas fa-tasks"></i> <span>任务管理</span></a>
            </li>
            <li>
                <a href="#"><i class="fas fa-chart-line"></i> <span>性能监控</span></a>
            </li>
            <li>
                <a href="#"><i class="fas fa-cog"></i> <span>系统设置</span></a>
            </li>
            <li>
                <a href="#" onclick="logout()"><i class="fas fa-sign-out-alt"></i> <span>退出登录</span></a>
            </li>
        </ul>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
        <!-- 头部 -->
        <div class="header">
            <h1 class="page-title"><i class="fas fa-server"></i> 主机管理</h1>
            <div class="user-info">
                <div class="user-avatar">A</div>
                <div>
                    <div id="user-name">管理员</div>
                    <div id="user-role" style="font-size: 0.8rem; color: #95a5a6;">管理员</div>
                </div>
                <button class="btn btn-light" onclick="refreshData()">
                    <i class="fas fa-sync-alt"></i> 刷新数据
                </button>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div style="display: flex; justify-content: space-between; margin-bottom: 20px;">
            <div>
                <button class="btn btn-primary" onclick="showAddHostModal()">
                    <i class="fas fa-plus"></i> 添加主机
                </button>
                <button class="btn btn-light">
                    <i class="fas fa-filter"></i> 筛选主机
                </button>
            </div>
            <div>
                <input type="text" class="form-control" style="width: 300px;" placeholder="搜索主机名称或IP...">
            </div>
        </div>

        <!-- 主机列表 -->
        <div class="card">
            <div class="card-header">
                <div class="card-title">主机列表</div>
                <div style="font-size: 0.9rem; color: #7f8c8d;">
                    共 <span id="host-count">3</span> 台主机
                </div>
            </div>
            <div class="card-body">
                <div class="host-card" id="hosts-container">
                    <!-- 主机卡片将通过JS动态生成 -->
                </div>
            </div>
        </div>

        <!-- 主机详情模态框 -->
        <div class="modal" id="host-detail-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; align-items: center; justify-content: center;">
            <div style="background: white; width: 90%; max-width: 800px; border-radius: 10px; overflow: hidden;">
                <div class="card-header">
                    <div class="card-title" id="detail-host-name">主机详情</div>
                    <button class="btn btn-light" onclick="closeModal('host-detail-modal')">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="card-body">
                    <div id="host-detail-content">
                        <!-- 主机详情内容将通过JS动态生成 -->
                    </div>

                    <h3 style="margin: 20px 0 10px;">执行命令</h3>
                    <div class="command-container">
                        <input type="text" class="command-input" id="command-input" placeholder="输入命令 (如: uptime, df -h, free -m, top -n 1)">
                        <button class="btn btn-primary" onclick="executeCommand()">
                            <i class="fas fa-play"></i> 执行
                        </button>
                    </div>

                    <div class="output-panel" id="command-output">
                        <!-- 命令输出结果将显示在这里 -->
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加主机模态框 -->
        <div class="modal" id="add-host-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; align-items: center; justify-content: center;">
            <div style="background: white; width: 90%; max-width: 500px; border-radius: 10px; overflow: hidden;">
                <div class="card-header">
                    <div class="card-title">添加新主机</div>
                    <button class="btn btn-light" onclick="closeModal('add-host-modal')">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="card-body">
                    <form id="add-host-form">
                        <div class="form-group">
                            <label class="form-label">主机名称</label>
                            <input type="text" class="form-control" name="hostname" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">IP地址</label>
                            <input type="text" class="form-control" name="ip" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">操作系统</label>
                            <select class="form-control" name="os">
                                <option value="Ubuntu 22.04">Ubuntu 22.04</option>
                                <option value="CentOS 8">CentOS 8</option>
                                <option value="Debian 11">Debian 11</option>
                                <option value="Windows Server 2022">Windows Server 2022</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">标签</label>
                            <input type="text" class="form-control" name="tags" placeholder="用逗号分隔 (如: web, production)">
                        </div>
                        <button type="submit" class="btn btn-primary" style="width: 100%;">
                            <i class="fas fa-save"></i> 保存主机
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentUser = null;
        let currentHostId = null;

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 尝试从cookie获取token
            const token = getCookie('access_token');
            if (!token) {
                // 如果没有token，重定向到登录页
                window.location.href = '/';
                return;
            }

            // 解析token获取用户信息
            try {
                const tokenData = JSON.parse(atob(token.split('.')[1]));
                currentUser = {
                    username: tokenData.sub,
                    name: tokenData.name,
                    role: tokenData.role
                };

                // 更新用户信息显示
                document.getElementById('user-name').textContent = currentUser.name;
                document.getElementById('user-role').textContent =
                    currentUser.role === 'admin' ? '管理员' :
                    currentUser.role === 'editor' ? '编辑者' : '查看者';

                // 加载主机数据
                loadHosts();
            } catch (e) {
                console.error('Token解析失败:', e);
                alert('登录信息无效，请重新登录');
                window.location.href = '/';
            }
        });

        // 加载主机数据
        async function loadHosts() {
            try {
                const response = await fetch('/api/hosts', {
                    method: 'GET',
                    credentials: 'include'
                });

                if (!response.ok) {
                    if (response.status === 401) {
                        alert('会话已过期，请重新登录');
                        window.location.href = '/';
                        return;
                    }
                    throw new Error(`请求失败: ${response.status}`);
                }

                const data = await response.json();
                renderHosts(data.hosts);
            } catch (error) {
                console.error('加载主机数据失败:', error);
                alert('加载主机数据失败: ' + error.message);
            }
        }

        // 渲染主机列表
        function renderHosts(hosts) {
            const container = document.getElementById('hosts-container');
            const countElement = document.getElementById('host-count');

            if (!hosts || hosts.length === 0) {
                container.innerHTML = '<div style="text-align: center; padding: 40px; color: #7f8c8d;">没有找到主机</div>';
                countElement.textContent = '0';
                return;
            }

            countElement.textContent = hosts.length;
            container.innerHTML = '';

            hosts.forEach(host => {
                const hostElement = document.createElement('div');
                hostElement.className = 'host-item';
                hostElement.dataset.id = host.id;

                // 状态样式
                const statusClass = host.status === 'online' ? 'online' : 'offline';
                const statusText = host.status === 'online' ? '在线' : '离线';

                // 资源使用率颜色
                const cpuClass = host.cpu > 80 ? 'danger' : host.cpu > 60 ? 'warning' : 'success';
                const memClass = host.memory > 80 ? 'danger' : host.memory > 60 ? 'warning' : 'success';
                const storageClass = host.storage > 90 ? 'danger' : host.storage > 80 ? 'warning' : 'success';

                hostElement.innerHTML = `
                    <div class="host-header">
                        <div class="host-name">${host.hostname}</div>
                        <div class="host-status ${statusClass}">${statusText}</div>
                    </div>
                    <div class="host-ip">${host.ip}</div>
                    <div>${host.os}</div>

                    <div class="host-details">
                        <div class="metric">
                            <div class="metric-value" style="color: ${getColorForValue(host.cpu)}">${host.cpu}%</div>
                            <div class="metric-label">CPU</div>
                        </div>
                        <div class="metric">
                            <div class="metric-value" style="color: ${getColorForValue(host.memory)}">${host.memory}%</div>
                            <div class="metric-label">内存</div>
                        </div>
                        <div class="metric">
                            <div class="metric-value" style="color: ${getColorForValue(host.storage)}">${host.storage}%</div>
                            <div class="metric-label">存储</div>
                        </div>
                    </div>

                    <div class="host-tags">
                        ${host.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                    </div>

                    <div style="margin-top: 15px; display: flex; gap: 10px;">
                        <button class="btn btn-light" style="flex: 1;" onclick="viewHostDetails('${host.id}')">
                            <i class="fas fa-info-circle"></i> 详情
                        </button>
                        ${currentUser.role !== 'viewer' ? `
                        <button class="btn btn-light" onclick="editHost('${host.id}')">
                            <i class="fas fa-edit"></i>
                        </button>
                        ${currentUser.role === 'admin' ? `
                        <button class="btn btn-light" onclick="deleteHost('${host.id}')">
                            <i class="fas fa-trash"></i>
                        </button>
                        ` : ''}
                        ` : ''}
                    </div>
                `;

                container.appendChild(hostElement);
            });
        }

        // 根据数值获取颜色
        function getColorForValue(value) {
            if (value > 80) return '#e74c3c';
            if (value > 60) return '#f39c12';
            return '#27ae60';
        }

        // 查看主机详情
        async function viewHostDetails(hostId) {
            try {
                const response = await fetch(`/api/hosts/${hostId}`, {
                    method: 'GET',
                    credentials: 'include'
                });

                if (!response.ok) {
                    throw new Error(`请求失败: ${response.status}`);
                }

                const host = await response.json();
                renderHostDetails(host);
                currentHostId = hostId;
                document.getElementById('host-detail-modal').style.display = 'flex';
            } catch (error) {
                console.error('获取主机详情失败:', error);
                alert('获取主机详情失败: ' + error.message);
            }
        }

        // 渲染主机详情
        function renderHostDetails(host) {
            document.getElementById('detail-host-name').textContent = host.hostname;

            const container = document.getElementById('host-detail-content');
            container.innerHTML = `
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                    <div>
                        <div class="form-group">
                            <label class="form-label">主机名称</label>
                            <div class="form-control">${host.hostname}</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">IP地址</label>
                            <div class="form-control">${host.ip}</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">操作系统</label>
                            <div class="form-control">${host.os}</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">状态</label>
                            <div class="form-control">
                                <span class="host-status ${host.status === 'online' ? 'online' : 'offline'}">
                                    ${host.status === 'online' ? '在线' : '离线'}
                                </span>
                            </div>
                        </div>
                    </div>

                    <div>
                        <div class="form-group">
                            <label class="form-label">CPU使用率</label>
                            <div class="form-control" style="color: ${getColorForValue(host.cpu)}">${host.cpu}%</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">内存使用率</label>
                            <div class="form-control" style="color: ${getColorForValue(host.memory)}">${host.memory}%</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">存储使用率</label>
                            <div class="form-control" style="color: ${getColorForValue(host.storage)}">${host.storage}%</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">最后检查时间</label>
                            <div class="form-control">${host.last_check}</div>
                        </div>
                    </div>
                </div>

                <div class="host-tags" style="margin-top: 10px;">
                    ${host.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                </div>
            `;
        }

        // 执行命令
        async function executeCommand() {
            const commandInput = document.getElementById('command-input');
            const command = commandInput.value.trim();

            if (!command) {
                alert('请输入要执行的命令');
                return;
            }

            try {
                const response = await fetch(`/api/hosts/${currentHostId}/execute`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ command: command }),
                    credentials: 'include'
                });

                if (!response.ok) {
                    throw new Error(`命令执行失败: ${response.status}`);
                }

                const result = await response.json();
                const outputPanel = document.getElementById('command-output');

                outputPanel.innerHTML = `$ ${result.command}\n${result.output}`;

                // 清空输入
                commandInput.value = '';
            } catch (error) {
                console.error('执行命令失败:', error);
                alert('执行命令失败: ' + error.message);
            }
        }

        // 显示添加主机模态框
        function showAddHostModal() {
            if (currentUser.role === 'viewer') {
                alert('您没有添加主机的权限');
                return;
            }

            document.getElementById('add-host-form').reset();
            document.getElementById('add-host-modal').style.display = 'flex';
        }

        // 添加新主机
        document.getElementById('add-host-form').addEventListener('submit', async function(e) {
            e.preventDefault();

            const formData = new FormData(this);
            const tags = formData.get('tags') ? formData.get('tags').split(',').map(tag => tag.trim()) : [];

            const hostData = {
                hostname: formData.get('hostname'),
                ip: formData.get('ip'),
                os: formData.get('os'),
                tags: tags
            };

            try {
                const response = await fetch('/api/hosts', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(hostData),
                    credentials: 'include'
                });

                if (!response.ok) {
                    throw new Error(`添加主机失败: ${response.status}`);
                }

                const newHost = await response.json();
                alert(`主机 ${newHost.hostname} 添加成功`);
                closeModal('add-host-modal');
                loadHosts();
            } catch (error) {
                console.error('添加主机失败:', error);
                alert('添加主机失败: ' + error.message);
            }
        });

        // 删除主机
        async function deleteHost(hostId) {
            if (!confirm('确定要删除此主机吗？此操作不可撤销。')) {
                return;
            }

            try {
                const response = await fetch(`/api/hosts/${hostId}`, {
                    method: 'DELETE',
                    credentials: 'include'
                });

                if (!response.ok) {
                    throw new Error(`删除主机失败: ${response.status}`);
                }

                alert('主机删除成功');
                loadHosts();
            } catch (error) {
                console.error('删除主机失败:', error);
                alert('删除主机失败: ' + error.message);
            }
        }

        // 刷新数据
        function refreshData() {
            loadHosts();
            if (currentHostId) {
                viewHostDetails(currentHostId);
            }
        }

        // 关闭模态框
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        // 登出
        async function logout() {
            try {
                const response = await fetch('/logout', {
                    method: 'POST',
                    credentials: 'include'
                });

                if (response.ok) {
                    window.location.href = '/';
                }
            } catch (error) {
                console.error('登出失败:', error);
                alert('登出失败: ' + error.message);
            }
        }

        // 获取Cookie
        function getCookie(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
            return null;
        }
    </script>
</body>
</html>